package com.haohan.jingyuan.user.controller;

import cn.hutool.json.JSONUtil;
import com.haohan.jingyuan.gateway.aspect.NeedLogin;
import com.haohan.jingyuan.gateway.dto.GwRequest;
import com.haohan.jingyuan.gateway.dto.GwResponse;
import com.haohan.jingyuan.user.dto.req.LoginRequest;
import com.haohan.jingyuan.user.dto.req.LogoutRequest;
import com.haohan.jingyuan.user.dto.resp.LoginResp;
import com.haohan.jingyuan.user.service.AdminService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * 管理员控制器
 * <p>
 * 负责管理员认证登录相关接口
 * </p>
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class AdminController {

    /**
     * 管理员服务
     */
    private final AdminService adminService;

    /**
     * 管理员登录
     *
     * @param request 登录请求（管理员用户名与密码）
     * @return 登录成功返回token，失败返回错误信息
     */
    @PostMapping("/admin/login")
    // @HeaderToBody
    public GwResponse<LoginResp> adminLogin(@Valid @RequestBody GwRequest<LoginRequest> request) {
        log.info("AdminController.adminLogin BEGIN ==> {}", JSONUtil.toJsonStr(request));
        LoginResp loginResp = adminService.login(request.getRequestData());
        GwResponse<LoginResp> response = null;
        if (loginResp == null) {
            response = GwResponse.error("用户名或密码错误");
        } else {
            response = GwResponse.success("登录成功", loginResp);
        }
        log.info("AdminController.adminLogin END ==> {}", JSONUtil.toJsonStr(response));
        return response;
    }

    /**
     * 管理员登出
     * <p>
     * 删除登录时生成的token，使token失效
     *
     * @param request 登出请求（包含token）
     * @return 登出成功或失败信息
     */
    @NeedLogin
    @PostMapping("/admin/logout")
    // @HeaderToBody
    public GwResponse<Void> adminLogout(@Valid @RequestBody GwRequest<LogoutRequest> request) {
        log.info("AdminController.adminLogout BEGIN ==> {}", JSONUtil.toJsonStr(request));
        boolean success = adminService.logout();
        GwResponse<Void> response = null;
        if (success) {
            response = GwResponse.success("登出成功");
        } else {
            response = GwResponse.error("登出失败");
        }
        log.info("AdminController.adminLogout END ==> {}", JSONUtil.toJsonStr(response));
        return response;
    }


}